import {
  forwardRef,
  ReactElement,
  useCallback,
  useImperativeHandle,
  useState,
} from 'react';
import { useRequest } from 'ahooks';
import { getCategoryList } from './service';
import { Input } from 'antd';
import { getMessage } from '@inbiz/react';
import { choeseData } from './index';
import './index.less';

const { Search } = Input;
type Iprops = {
  resultChange: (res: any) => void;
  typeChage: (res: any) => void;
  searchChange: (searchWord: string) => void;
  pageSize: number;
  topFolderId: number;
  value: choeseData;
  categoryType: 1 | 0;
};

type resultData = {
  CmsCategoryList: [];
  PageCount: number;
  PageIndex: number;
  PageSize: number;
  Total: number;
};

function DocSearch(props: Iprops, ref: any): ReactElement {
  const [searchWord, setSearchWord] = useState('');

  // 准备请求
  const { runAsync, loading } = useRequest(getCategoryList, {
    manual: true,
  });
  // 根据搜索词获取相关的数据
  const getSearWord = useCallback(
    (params: {
      categoryType: number;
      categoryName: string;
      pageIndex: number;
      pageSize: number;
    }) => {
      return runAsync(params)
        .then((res: any | resultData) => {
          props.typeChage('list');
          props.resultChange(res);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    [],
  );

  // 搜索点击时发生的事件
  const getSearchList = useCallback(
    (res: string) => {
      if (res) {
        props.searchChange(res);
        getSearWord({
          categoryType: props.categoryType,
          categoryName: res,
          pageIndex: 1,
          pageSize: 10,
        });
      }
    },
    [props.topFolderId],
  );

  // 搜索文字改变时触发
  const onChange = useCallback(
    (e: any) => {
      setSearchWord(e.target.value);
      if (!e.target.value || e.target.value?.length < 0) {
        props.typeChage('tree');
      }
    },
    [props.topFolderId],
  );

  // 对外提供搜索方法
  useImperativeHandle(ref, () => ({
    search: (size: number, pageIndex: number) => {
      getSearWord({
        categoryType: props.categoryType,
        categoryName: searchWord,
        pageIndex: pageIndex,
        pageSize: size,
      });
    },
  }));

  return (
    <>
      <Search
        className="serchInput"
        onSearch={getSearchList}
        onChange={onChange}
        placeholder={getMessage('ClassPicker.pleaseEnterKeyWord')} // 请输入关键词
        value={searchWord}
      ></Search>
    </>
  );
}
export default forwardRef(DocSearch);
